#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t mutex;
pthread_cond_t cond;
int sharedData = 0;
bool dataReady = false;

void* producer(void* arg) {
    while (true) {
        sleep(1); // 模拟生产数据的时间
        pthread_mutex_lock(&mutex);
        sharedData++;
        dataReady = true;
        cout << "Producer produced data: " << sharedData << endl;
        pthread_cond_signal(&cond); // 通知消费者数据已准备好
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

void* consumer(void* arg) {
    while (true) {
        pthread_mutex_lock(&mutex);
        while (!dataReady) {
            pthread_cond_wait(&cond, &mutex); // 等待数据准备好
        }
        cout << "Consumer consumed data: " << sharedData << endl;
        dataReady = false;
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main() {
    pthread_t prodThread, consThread;

    pthread_mutex_init(&mutex, nullptr);
    pthread_cond_init(&cond, nullptr);

    pthread_create(&prodThread, nullptr, producer, nullptr);
    pthread_create(&consThread, nullptr, consumer, nullptr);

    pthread_join(prodThread, nullptr);
    pthread_join(consThread, nullptr);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}
